#include "cutemap.h"

CuteMap::CuteMap(QGeoMappingManager *manager, QGraphicsItem *parent) :
    QGraphicsGeoMap(manager,parent)
{
    me = new QGeoMapCircleObject();
    me->setRadius(-1);
    QBrush brush;
    brush.setColor(QColor(255,255,255,100));
    brush.setStyle(Qt::SolidPattern);
    me->setBrush(brush);

    m_route = new QGeoMapPolylineObject();

    QPen pen = m_route->pen();
    pen.setWidth(5);
    pen.setColor(Qt::green);
    m_route->setPen(pen);

    QGraphicsGeoMap::addMapObject(m_route);
    QGraphicsGeoMap::addMapObject(me);
    firstTime = true;
}

void CuteMap::setCenter(const QGeoCoordinate & center) {
    QGraphicsGeoMap::setCenter(center);
    me->setRadius(10);
    me->setCenter(center);
}

void CuteMap::animatedCenterTo(const QGeoCoordinate & center) {
    if (firstTime) {
        m_previousPoints.append(center);
    } else {
        m_previousPoints.append(this->center());
    }
    m_route->setPath(m_previousPoints);

    QPropertyAnimation *latAnim = new QPropertyAnimation(this, "centerLatitude");
    latAnim->setEndValue(center.latitude());
    latAnim->setDuration(200);
    QPropertyAnimation *lonAnim = new QPropertyAnimation(this, "centerLongitude");
    lonAnim->setEndValue(center.longitude());
    lonAnim->setDuration(200);

    QParallelAnimationGroup *group = new QParallelAnimationGroup;
    group->addAnimation(latAnim);
    group->addAnimation(lonAnim);
    group->start(QAbstractAnimation::DeleteWhenStopped);
}

void CuteMap::mousePressEvent(QGraphicsSceneMouseEvent *event)
 {
     panActive = true;
     event->accept();
 }

 void CuteMap::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
 {
     panActive = false;
     event->accept();
 }

 void CuteMap::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
 {
     if (panActive) {
         QPointF delta = event->lastPos() - event->pos();
         pan(delta.x(), delta.y());
     }
     event->accept();
 }

 void CuteMap::wheelEvent(QGraphicsSceneWheelEvent *event)
 {
     qreal panx = event->pos().x() - size().width() / 2.0;
     qreal pany = event->pos().y() - size().height() / 2.0;
     pan(panx, pany);
     if (event->delta() > 0) {   // zoom in
         if (zoomLevel() < maximumZoomLevel()) {
             setZoomLevel(zoomLevel() + 1);
         }
     } else {                    // zoom out
         if (zoomLevel() > minimumZoomLevel()) {
             setZoomLevel(zoomLevel() - 1);
         }
     }
     pan(-panx, -pany);
     event->accept();
 }

